﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using Windows.UI;

namespace Enough.Converter
{
    /// <summary>
    /// Value converter for converting hexadecimal strings to a SolidColorBrush
    /// </summary>
    public class HexStringToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                value = parameter;
            }
            if (value == null || (value.ToString().Length < 6))
            {
                return null;
            }
            string strValue = value.ToString();
            if (strValue[0] == '#')
            {
                strValue = strValue.Substring(1);
            }
            uint colorValue = uint.Parse(strValue, System.Globalization.NumberStyles.HexNumber);
            return Color.FromArgb(0xff, (byte)((colorValue & 0xff0000) >> 16), (byte)((colorValue & 0x00ff00) >> 8), (byte)(colorValue & 0x0000ff));
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Color color = (Color)value;
            if (color == null)
            {
                return null;
            }
            StringBuilder builder = new StringBuilder();
            //builder.Append('#');
            appendHex(color.R, builder);
            appendHex(color.G, builder);
            appendHex(color.B, builder);
            return builder.ToString();
        }

        static char[] hexDigits = {
         '0', '1', '2', '3', '4', '5', '6', '7',
         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    

      public void appendHex(byte colorValue, StringBuilder builder)
        {
            builder.Append(hexDigits[colorValue >> 4]);
            builder.Append(hexDigits[colorValue & 0xF]);
        }
    }
}
